#!/usr/bin/env python
#  TCP-Server

import socket
import subprocess
sk_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk_obj.bind(('', 12000))
sk_obj.listen(5)
while True:
    conn, ipaddr = sk_obj.accept()
    print('connection from ip: %s' % ipaddr[0])
    while True:
        try:
            from_recv = conn.recv(8096)
            if len(from_recv) == 0:
                continue
            print('from ip : %s information : %s' % (ipaddr[0], from_recv))
            res = subprocess.Popen(from_recv.decode('utf-8').strip(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            msg = res.stdout.read()
            if len(msg) == 0:
                msg = res.stderr.read()
            conn.send(msg)
        except Exception:
            break
    conn.close()
